﻿// 开发者:micropu
// 公司:佛山远钧智慧科技有限公司

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.NET.Application;
/// <summary>
/// 自定义数据处理适配器
/// </summary>
internal class MyFixedHeaderRequestInfo : CustomFixedHeaderDataHandlingAdapter<MyRequestInfo>
{
    public override int HeaderLength => 32;

    protected override MyRequestInfo GetInstance()
    {
        return new MyRequestInfo();
    }
}

/// <summary>
/// 请求信息
/// </summary>
internal class MyRequestInfo : IFixedHeaderRequestInfo
{
    public byte Header { get; internal set; }
    public uint ContentLen { get; internal set; }
    public uint PackageIndex { get; internal set; }
    public uint PackageCount { get; internal set; }
    public byte Version { get; internal set; }
    public ushort Command { get; internal set; }
    public byte[] SessionId { get; internal set; }
    public byte[] Content { get; internal set; }
    public byte Flag { get; internal set; }
    public byte Tail { get; internal set; }

    /// <summary>
    /// 接口实现，标识数据长度
    /// </summary>
    public int BodyLength { get; private set; }

    public bool OnParsingBody(byte[] body)
    {
        if (body.Length == this.BodyLength)
        {
            this.Content = body.Take(BodyLength - 2).ToArray();
            this.Flag = body[BodyLength - 2];
            this.Tail = body[BodyLength - 1];
            return true;
        }
        return false;
    }

    public bool OnParsingHeader(byte[] header)
    {
        this.Header = header[0];
        this.ContentLen = BitConverter.ToUInt32(header, 1);
        this.PackageIndex = BitConverter.ToUInt32(header, 5);
        this.PackageCount = BitConverter.ToUInt32(header, 9);
        this.Version = header[13];
        this.Command = BitConverter.ToUInt16(header, 14);
        this.SessionId = header.Skip(16).Take(16).ToArray();
        this.BodyLength = (int)this.ContentLen + 2; // Content + Flag + Tail
        return true;
    }
}